package com.augurit.common.base.schedule;

import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.system.service.org.IOmUserService;
import com.augurit.common.system.web.org.form.OmUserForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.common.util.SmsWebService;
import com.augurit.gzcgwsp.common.util.WSClient;
import com.augurit.gzcgwsp.mail.service.ISendMailService;
import com.augurit.gzcgwsp.printDoc.dao.YwPrintDocDao;
import com.augurit.gzcgwsp.printDoc.entity.YwPrintDoc;
import com.augurit.gzcgwsp.ywcmn.entity.YwComFsxx;
import com.augurit.gzcgwsp.ywcmn.service.IYwComFsxxService;
import com.augurit.wf.common.dao.Jbpm4TaskDao;
import com.augurit.wf.common.dao.SMToSendDao;
import com.augurit.wf.common.entity.Jbpm4Task;
import com.augurit.wf.common.entity.SMToSend;
import com.augurit.wf.common.form.WfSendMessageForm;

public class JdkExecutorJobTask extends JdkExecutorJob{
	private static Logger log=Logger.getLogger(JdkExecutorJobTask.class);
	@Autowired
	private Jbpm4TaskDao jbpm4TaskDao;
	
	@Autowired
	private SMToSendDao sMToSendDao;
	
	@Autowired
	private IOmUserService omUserService;
	
	@Autowired
	private YwPrintDocDao ywPrintDocDao;
	
	@Autowired
	private IYwComFsxxService ywComFsxxService;
	@Autowired
	private ISendMailService sendMailService;
	@Override
	public void run() {
		try {
			//scanAllTask();
//			//sendPreNotice();
//			//发送短信
			sendSms();
			
			//log.info("邮件定时器开始启动..........");
			//sendMailService.insertMail();//先插入邮件
			//sendMailService.send();//发送邮件
			//log.info("邮件定时器结束..........");
		} catch (Exception e) {
			e.printStackTrace();
		}
		//发行政许可书到oa
		//sendDoc();
	}
	
	/**
	 * 发行政许可书到oa
	 */
	private void sendDoc(){
		Session session=this.ywPrintDocDao.getSessionFactory().openSession();
		StringBuffer sb=new StringBuffer();
		sb.append("select t.template_code,t.bus_memo1,doc.* from ( \r");
		sb.append("select   temp.template_code,ins.master_entity_key,ins.bus_memo1 from \r");
		sb.append("JBPM4_HIST_PROCINST proc,WF_BUS_INSTANCE ins,WF_BUS_TEMPLATE temp \r");
		sb.append(" where proc.id_=ins.proc_inst_id  \r");
		sb.append("and ins.template_id=temp.id    and proc.state_='ended' ) \r");
		sb.append(" t inner join YW_PRINT_DOC doc on doc.yw_id=t.master_entity_key and \r");
		sb.append(" doc.template_code=t.template_code  and doc.file_code='zyxzxkjds' and doc.sendoa is  null \r");
		List list=this.queryForList(sb.toString());
		log.info("待发送oa的数据"+list.size());
		try {
			for(int i=0;i<list.size();i++){
				// sessions=this.ywPrintDocDao.getSessionFactory().openSession();
				String context = new File(getClass().getClassLoader().getResource("").toURI()).getPath();
				Map map=(Map) list.get(i);
				String sqdw=(String) map.get("bus_memo1");
				String creator=(String) map.get("creator");
				String filePath=(String) map.get("path");
				String docid=(String) map.get("id");
				log.info("docid"+docid+"创建人:"+creator+"filePath"+filePath);
				context=context.substring(0,context.indexOf("WEB-INF")-1);
				String filepath=context+filePath;
				filepath=filepath.replace("/",File.separator);
				log.info("filepath"+filepath);
				try {
					//查询用户的用户编码
					String usersql="select * from OM_USER where user_name='"+creator+"'";
					List users=this.queryForList(usersql);
					if(users.size()>0){
						Map userdata=(Map) users.get(0);
						String userCode=(String) userdata.get("user_code");
						String result=WSClient.invoke(filepath,sqdw+"行政许可决定书", userCode);
						log.info("发送oa文件返回结果"+result);
						//if("Success".equals(result)){
							//YwPrintDoc doc=(YwPrintDoc) sessions.get(YwPrintDoc.class, Long.valueOf(docid));
							String docsql="update YW_PRINT_DOC set sendoa='1' where id="+Long.valueOf(docid);
							this.updateDateBase(docsql);
							//doc.setSendoa("1");//改为已发送
							//sessions.saveOrUpdate(doc);
							//sessions.close();
						//}
					}
				} catch (Exception e) {
					e.printStackTrace();
					log.error("发送oa出现文件错误"+e);
				}
			}
		} catch (Exception e) {
			log.error("发送出现文件错误"+e);
		}
		session.close();
		
	}

	
	private void sendSms(){
		Session session=this.sMToSendDao.getSessionFactory().openSession();
		try {
			List<SMToSend> sends=this.getSmsDatas();
			log.info("发送的短信数量"+sends.size());
			for(SMToSend entity:sends){
				if(StringUtils.isNotBlank(entity.getDestAddr())){
					String result=SmsWebService.sendSms(entity);
					if("操作成功".equals(result)){
						String hql = "update SMToSend sm set sm.sts='1' where sm.id=:id";
						Query query = session.createQuery(hql);
						query.setLong("id", entity.getSmId());
						query.executeUpdate();
					}else{
						String hql = "update SMToSend sm set sm.sts='2' where sm.id=:id";
						Query query = session.createQuery(hql);
						query.setLong("id", entity.getSmId());
						query.executeUpdate();
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		session.close();
	}
	
	
	/**
	 * 获取发送的数据
	 * @return
	 */
	private List<SMToSend> getSmsDatas(){
		Session session=this.sMToSendDao.getSessionFactory().openSession();		
		List<SMToSend> list=new ArrayList<SMToSend>();
		try {
			Criteria cri=session.createCriteria(SMToSend.class);
			cri.add(Restrictions.isNull("sts"));
			list = cri.list();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		session.close();
		return list;
	}
	
	private List<Jbpm4Task> getList(){
		Session session=jbpm4TaskDao.getSessionFactory().openSession();		
		List<Jbpm4Task> jbpm4TaskList=new ArrayList<Jbpm4Task>();
		try {
			Criteria cri=session.createCriteria(Jbpm4Task.class);
			cri.add(Restrictions.isNotNull("jms"));
			jbpm4TaskList = cri.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		session.close();
		return jbpm4TaskList;
	}
	
	//扫描Jbpm4_Task表
	public List<Jbpm4Task> scanAllTask(){
		List<Jbpm4Task> list = null;
		try {
			String sql = "from jbpm4Task where jms is not null";
			list = this.getList();
			log.info("发送到短信的接口数量："+list.size());
			if(list != null && list.size()>0){
				for(Jbpm4Task task :list){
					WfSendMessageForm form = convertJbpm4TaskToWfSendMessageForm(task);
					if(form!=null && "1".equals(form.getSmsRemind())){
						//把task转化到SMToSend
						try {
							saveSmToSend(task);
						} catch (RuntimeException e) {
							log.error("保存信息出错 ============"+e);
						}
						//设置为不需要发送短信
						updateJbpm4Task(task,form);
						
					}
				}
			}
		} catch (RuntimeException e) {
			log.error("保存信息出错 ============"+e);
		}
		return list;
	}
	
	//设置为不需要发送短信
	public void updateJbpm4Task(Jbpm4Task jbpm4Task,WfSendMessageForm form){
		if(jbpm4Task != null && form != null){
			form.setSmsRemind("0");
			jbpm4Task.setJms(Struts2Utils.getJsonString(form));
			Session session=jbpm4TaskDao.getSessionFactory().openSession();
			session.saveOrUpdate(jbpm4Task);			
			//session.flush();
			session.close();
		}
		
	}
	public void saveSmToSend(Jbpm4Task jbpm4Task){
		if(jbpm4Task != null){
			SMToSend entity = convertJbpm4TaskToSMToSend(jbpm4Task);
			Session session=sMToSendDao.getSessionFactory().openSession();
			session.saveOrUpdate(entity);
			//session.flush();
			session.close();
		}
	}
	
	
	//将Jbpm4Task转化为SMToSend
	public SMToSend convertJbpm4TaskToSMToSend(Jbpm4Task jbpm4Task){
		SMToSend sMToSend = null;
		if(jbpm4Task != null && StringUtils.isNotBlank(jbpm4Task.getAssignee())){
			sMToSend = new SMToSend();
			OmUserForm omUserForm = omUserService.get(jbpm4Task.getAssignee());
			sMToSend.setDestAddr(omUserForm.getMobile());//发送目标手机号码
			Date date = new Date();
			sMToSend.setSubTime(date);
			//date.setTime(date.getTime()+5*1000); //延迟5秒后发送
			sMToSend.setSendTime(date);
//			WfTaskSummaryForm summaryForm = wfTaskSummaryService.getByTaskInstDbid(jbpm4Task.getTaskInstDbid());
//			String title = summaryForm.getTaskTopic();
			String smContent ="城管委审批系统：您有案件需及时处理。（请勿回复）";
			sMToSend.setSmContent(smContent);
		}
		return sMToSend;
	}
	
	//将Jbpm4Task里的jms
	public WfSendMessageForm convertJbpm4TaskToWfSendMessageForm(Jbpm4Task jbpm4Task){
		WfSendMessageForm form = null;
		if(jbpm4Task != null){
			String jms = jbpm4Task.getJms();
			if(jms != null && jms.trim().length()>0){
				form = new WfSendMessageForm();
				JSONObject jo  = JSONObject.fromObject(jms);
				form = (WfSendMessageForm)JSONObject.toBean(jo, WfSendMessageForm.class);
			}
		}
		return form;
	}
	
	//提前一天通知经办人
	public void sendPreNotice(){
		SMToSend sMToSend = null;
		List<YwComFsxx> preNoiceList = ywComFsxxService.getPreNoice();
		if(preNoiceList.size()>0){
			sMToSend = new SMToSend();
			for(int i=0;i<preNoiceList.size();i++){
				try {
					YwComFsxx ywComFsxx = preNoiceList.get(i);
					sMToSend.setDestAddr(ywComFsxx.getMoblie());//发送目标手机号码				
					Date date = new Date();
					sMToSend.setSubTime(date);
					date.setTime(date.getTime()+3*1000); //延迟3秒后发送
					sMToSend.setSendTime(date);
					String smContent ="城管委审批系统：您在审批系统有待办，请及时处理。（请勿回复）";
					sMToSend.setSmContent(smContent);
					Session session=sMToSendDao.getSessionFactory().openSession();
					session.saveOrUpdate(sMToSend);
					session.flush();
					session.close();
					ywComFsxx.setSendDate(new Date());
					ywComFsxx.setIsSend("1");
					ywComFsxxService.saveOrUpdateYwComFsxx(ywComFsxx);
				} catch (HibernateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	
	
	/**
	 * 简单SQL查询  
	 * 
	 * @param sql
	 * @return
	 */
	public  List queryForList(String sql) {
		Session session=this.jbpm4TaskDao.getSessionFactory().openSession();
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		List<Map> tempList = new ArrayList<Map>();
		try {
			long timeBefore = System.currentTimeMillis();
			conn = session.connection();
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			ResultSetMetaData meta = rs.getMetaData();
			int columnCount = meta.getColumnCount();
			while(rs.next()) {
				Map<String, String> map = new LinkedHashMap<String, String>();
				for(int i=1; i<=columnCount; i++) {
					String colName = meta.getColumnLabel(i).toLowerCase();
					String colValue = rs.getString(i);
					map.put(colName, colValue);
				}
				tempList.add(map);
			}
		
		}catch(Exception e) {
			log.error("查找异常", e);
		}finally {
				try {
					st.close();
					rs.close();
					conn.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			session.close();
		}
		
		return tempList;
	}
	
	
	

	/**
	 * sql修改某张表
	 * @param sql
	 * @return
	 */
	public  int updateDateBase(String sql) {
		Session session=this.ywPrintDocDao.getSessionFactory().openSession();
		Connection conn = null;
		Statement st = null;
		int num = 0;
		try {
			long timeBefore = System.currentTimeMillis();
			conn = session.connection();
			st =conn.createStatement();
			num = st.executeUpdate(sql);
		}catch(Exception e) {
			log.error("更错误", e);
		}finally {
			session.close();
		}
		
		return num;
	}
	
	
	
}
